package com.linkivr.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.linkivr.dao.*;
import com.linkivr.model.*;
import com.linkivr.util.GL;

@Component("unitDao")
public class UnitDaoImpl implements UnitDao {

	private SessionFactory sessionFactory;

	private String tabName = "T_unit";
	private String tabId = "unit_id";

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void add(T_unit tabObj) {
		
		sessionFactory.getCurrentSession().merge(tabObj);
	}

	public int delete(int id) {
		
		return sessionFactory.getCurrentSession().createQuery("delete " + tabName + "  where " + tabId + "=:id ")
				.setInteger("id", id).executeUpdate();
	}

	public void update(T_unit tabObj) {
		sessionFactory.getCurrentSession().merge(tabObj);
	}

	@SuppressWarnings("unchecked")
	public List<T_unit> queryAll() {
		
		String hql = "from " + tabName;
		GL.info(hql);
		return sessionFactory.getCurrentSession().createQuery(hql).list();
	}

	@SuppressWarnings("unchecked")
	public List<T_unit> queryAll(int start, int limit) {
		String hql = "from " + tabName + "  order by " + tabId + " desc ";
		GL.info(hql);
		return sessionFactory.getCurrentSession().createQuery(hql).setFirstResult(start).setMaxResults(limit).list();
	}

	public T_unit query(int id) {
		String hql = "from " + tabName + " where  " + tabId + "=:id";
		GL.info(hql);
		return (T_unit) sessionFactory.getCurrentSession().createQuery(hql).setInteger("id", id).uniqueResult();

	}

	public int queryCount() {
		Integer count = 0;
		Long lo = (Long) sessionFactory.getCurrentSession().createQuery("select count(*) from " + tabName)
				.uniqueResult();
		count = new Integer(String.valueOf(lo));
		GL.info("queryCount" + count);
		return count;
	}

}
